package com.codebo.homiematch.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.codebo.homiematch.common.BaseResponse;
import com.codebo.homiematch.common.ErrorCode;
import com.codebo.homiematch.common.ResultUtils;
import com.codebo.homiematch.config.CosClientConfig;
import com.codebo.homiematch.exception.BusinessException;
import com.codebo.homiematch.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/img")
public class ImgController
{
    @Resource
    private CosManager cosManager;
    @Resource
    private CosClientConfig cosClientConfig;

    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile multipartFile, @RequestParam(value = "id") int id)
    {
        System.out.println(1);
        String originalFilename = multipartFile.getOriginalFilename();
        UUID uuid = UUID.randomUUID();
        //去掉uuid的-
        String uuidStr = uuid.toString().replace("-", "");
        //文件名为时间加上uuid

        String filename = DateUtil.today() + uuidStr;
        String filepath = String.format("/" + id + "/%s", filename + "." + FileUtil.getSuffix(originalFilename));
        File tempFile = null;
        try
        {
            tempFile = File.createTempFile(filepath, null);
            multipartFile.transferTo(tempFile);
            cosManager.putObject(filepath, tempFile);
            return ResultUtils.success(cosClientConfig.getHost() + filepath);
        } catch (Exception e)
        {
            log.error("上传文件失败，路径为{}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally
        {
            if (tempFile != null)
            {
                boolean delete = tempFile.delete();
                if (!delete)
                {
                    log.error("删除临时文件失败，路径为{}", filepath);
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
                }

            }
        }
    }
}
